using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class app_frame_help : System.Web.UI.Page
{
    string strPagesetRowID = "a50d8e7cd7a5db90"; // format_masks
    DataSet dseInputInfo = new DataSet();
    DataSet dsePageInfo = new DataSet();
    HtmlForm frmObj;
    string strErrMessage = "";
    string refererURL = "";
    string dtFormat = "MM-dd-yyyy HH:mm:ss";
    protected void Page_Load(object sender, EventArgs e)
    {
        putBreaksBeforeDIV();
        //if (Request.UrlReferrer.ToString().IndexOf("DisplayGrid") > 0)
        //    refererURL = Request.UrlReferrer.ToString();
        
        security hdds = new security();
        if (Session["userid"] == null) Response.Redirect(hdds.SessionExpiryURL);
        if (Session["userid"].ToString() == "") Response.Redirect(hdds.SessionExpiryURL);


        //Code added by Sampath on 16-Nov-2011 for IPP Vertical privilege
        if (Request.QueryString["mn"] != null)
        {
            if (!hdds.checkObjectMenuAccess(Request.QueryString["mn"]))
            {
                lbl_message.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
                tblmain.Visible = false;
                return;
            }
        }

        //Code added by Sampath on 15-Nov-2011 for IPP Vertical privilege
        if (Request.QueryString["PK"] != null && Request.QueryString["pgs_id"] != null)
        {
            if (!hdds.checkRecordAccess(Request.QueryString["PK"].ToString(), Request.QueryString["pgs_id"].ToString()))
            {
                lbl_message.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
                tblmain.Visible = false;
                return;
            }
        }


        setRequestURL();
        //loadDynamicControls();
        if (this.Master.FindControl("Form1") != null)
        {
            frmObj = (HtmlForm)this.Master.FindControl("Form1");
        }
        PageInfoLoad PIL = new PageInfoLoad();
        dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowID);
        if (!Page.IsPostBack)
        {
            loadOwneridDropDown();
        }

        CheckForChangeOwner();
        

        CheckEditOperation();
        //p_help_help_desc.Visible=false;
        if (IsPostBack) return;
        //p_job_schedules_jb_sch_time.Attributes.Add("onchange", "javascript:alert('ss');");
        //p_job_schedules_jb_sch_time.Attributes.Add("onselect", "javascript:alert('ss');");
        //p_format_masks_message_validator_tip.Attributes.Add("onchange", "javascript:putValues();");
        //p_format_masks_name.Text = getSeqNumber();
        //loadCategory();
        //loadRecurrTypes();
        if (btnUpdate.Visible)
        {
            loadMasterValues();
        }
        //if (Request.QueryString["CPY"] != null)//to get the new ID
        //    if (Request.QueryString["CPY"].ToString() == "0")
        //        p_job_schedules_jb_sch_id.Text = getSeqNumber();
        if (Request.QueryString["CPY"] != null)
        {
            if (Request.QueryString["CPY"] == "0")
            {
                loadMasterValues();
                //p_format_masks_owner_id.SelectedValue = Session["user_afrowid"].ToString();
                p_format_masks_owner_id.Value = Session["user_afrowid"].ToString();
                txt_p_format_masks_owner_id.Text = Session["userid"].ToString();
                //loadChildValues();
                //showParamterContent(true, Request.QueryString["PK"].ToString());
                //p_format_masks_name.Text = getSeqNumber();
            }
        }
        getpageicons(); // Added by srivatsan
        isViewMode();
    }
    private void isViewMode()
    {
        if (HttpContext.Current.Request.QueryString["VMODE"] != null)
            if (HttpContext.Current.Request.QueryString["VMODE"] == "1")
            {
                DynamicDisplayI ddi = new DynamicDisplayI();
                HtmlTable ht = (HtmlTable)frmObj.FindControl("ContentPlaceHolder3").FindControl("tblmain");
                ddi.disableControls(ht);
                ddi = null;
            }
    }    
    private void putBreaksBeforeDIV()
    {
        lbl_space_1.Text = "<br />";
        lbl_space_2.Text = "<br />";
    }
    private void setRequestURL()//implemented by sanal on 13 Dec 2007
    {
        if (!IsPostBack)
            //hfRequestURL.Value = Request.UrlReferrer.ToString();
            hfRequestURL.Value = "DisplayGrid.aspx?pgs_id=" + Request.QueryString["pgs_id"].ToString() + "&mn=" + Request.QueryString["mn"].ToString();
        
    }   
    private void loadMasterValues()
    {
        try
        {
            string sPageKey = "";
            if (Request.QueryString["PK"] != null)
                sPageKey = Request.QueryString["PK"].ToString();
            if (sPageKey == "") return;
            HDDatabase hd = new HDDatabase();
            DataSet ds = new DataSet();
            ds = hd.GetDataset("select * from sy_format_masks where af_row_id='" + sPageKey + "'");
            
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    //function added by bala on 18-Nov-2011 for IPP Tech check 
                    //CommonFunctions.decodeData(ds);
                    p_format_masks_af_row_id.Value = sPageKey;
                    p_format_masks_name.Text = ds.Tables[0].Rows[0]["name"].ToString();
                    p_format_masks_type.SelectedValue = ds.Tables[0].Rows[0]["type"].ToString();
                    p_format_masks_mask_string.Text = ds.Tables[0].Rows[0]["mask_string"].ToString();
                    p_format_masks_tooltip_message.Text = ds.Tables[0].Rows[0]["tooltip_message"].ToString();
                    p_format_masks_message_validator_tip.SelectedValue = ds.Tables[0].Rows[0]["message_validator_tip"].ToString();
                    if (ds.Tables[0].Rows[0]["is_valid_empty"].ToString() == "")
                        p_format_masks_is_valid_empty.SelectedValue = "False";
                    else
                        p_format_masks_is_valid_empty.SelectedValue = ds.Tables[0].Rows[0]["is_valid_empty"].ToString() == "False" ? "False" : "True";                    
                    p_format_masks_maximum_value.Text = ds.Tables[0].Rows[0]["maximum_value"].ToString();
                    p_format_masks_maximum_value_message.Text = ds.Tables[0].Rows[0]["maximum_value_message"].ToString();
                    p_format_masks_maximum_value_blurred_message.Text = ds.Tables[0].Rows[0]["maximum_value_blurred_message"].ToString();
                    p_format_masks_minimum_value.Text = ds.Tables[0].Rows[0]["minimum_value"].ToString();
                    p_format_masks_minimum_value_message.Text = ds.Tables[0].Rows[0]["minimum_value_message"].ToString();
                    p_format_masks_minimum_value_blurred_message.Text = ds.Tables[0].Rows[0]["minimum_value_blurred_message"].ToString();
                    p_format_masks_invalid_value_message.Text = ds.Tables[0].Rows[0]["invalid_value_message"].ToString();
                    p_format_masks_invalid_value_blurred_message.Text = ds.Tables[0].Rows[0]["invalid_value_blurred_message"].ToString();
                    p_format_masks_empty_value_message.Text = ds.Tables[0].Rows[0]["empty_value_message"].ToString();
                    p_format_masks_empty_value_blurred_message.Text = ds.Tables[0].Rows[0]["empty_value_blurred_message"].ToString();
                    p_format_masks_prompt_character.Value = ds.Tables[0].Rows[0]["prompt_character"].ToString();
                    //p_format_masks_owner_id.SelectedValue = ds.Tables[0].Rows[0]["owner_id"].ToString();
                    p_format_masks_owner_id.Value = ds.Tables[0].Rows[0]["owner_id"].ToString();
                    LoadEditPage LEP = new LoadEditPage();
                    txt_p_format_masks_owner_id.Text = LEP.GetUserIDFromAfrowid(ds.Tables[0].Rows[0]["owner_id"].ToString());
                    LEP = null;
                    if (ds.Tables[0].Rows[0]["clear_mask_blur"].ToString() == "")
                        p_format_masks_clear_mask_blur.SelectedValue = "False";
                    else
                        p_format_masks_clear_mask_blur.SelectedValue = ds.Tables[0].Rows[0]["clear_mask_blur"].ToString() == "False" ? "False" : "True";
                    if (ds.Tables[0].Columns.Contains("validation_expression"))
                        p_format_masks_validation_expression.Value = ds.Tables[0].Rows[0]["validation_expression"].ToString();
                }
            }

            ds = null;
            hd = null;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in messages.aspx:loadMasterValues: " + e.Message);
        }
    }
    private string getDateTimeValue(string inp)
    {
        try
        {
            DynamicDisplayI DDI = new DynamicDisplayI();
            string sTemp = DDI.getUsersDateTime(inp);
            if (sTemp == "") sTemp = inp;
            DateTime dt = DateTime.Parse(sTemp);
            return dt.ToString("MM-dd-yyyy HH:mm:ss");
        }
        catch (Exception e)
        {
            return inp;
        }
    }
    private void loadDynamicControls()
    {
        //if (IsPostBack) return;
        HiddenField hf = new HiddenField();
        hf.ID = "hf_ref_url";
        hf.EnableViewState = true;
        if (refererURL.Length > 0) hf.Value = refererURL;
        lbl_message.Controls.Add(hf);
    }

    private void loadRecurrTypes()
    {
        
    }
    private void loadCategory()
    {
        
    }
    private bool CheckEditOperation()
    {
        bool blnStatus = true;
        string strPageKey = "";
        bool IsEdit = false;
        if (Page.IsPostBack == false)
        {
            if (Request.QueryString["PK"] != null)
            {
                strPageKey = Request.QueryString["PK"].ToString();
                IsEdit = true;
            }
            if (IsEdit)
            {
                Master MA = new Master();
                blnStatus = MA.EditOperation(dsePageInfo, frmObj, strPageKey);
              
                if (blnStatus == false)
                {
                    strErrMessage = MA.ErrorMessage;
                    Response.Write("<font color='red'>Error : " + strErrMessage + "</font>");
                }
            }
        }
        if (Request.QueryString["CPY"] != null)
        {
            if (Request.QueryString["CPY"] == "0")
            {
                btnSave.Visible = true;
                btnUpdate.Visible = false;
            }
        }
        else if (Request.QueryString["PK"] == null)
        {
            btnSave.Visible = true;
            btnUpdate.Visible = false;
        }
        else
        {
            btnUpdate.Visible = true;
            btnSave.Visible = false;
        }
        return blnStatus;
    }



    private bool SaveData()
    {
        validateOwnerid();
        bool blnStatus = true;
        ScreenReader SR = new ScreenReader();
        dseInputInfo = SR.CaptureData(strPagesetRowID, frmObj, dsePageInfo,true);
        if (SR.errormessage != "")
        {
            strErrMessage = SR.errormessage;
            return false;
        }
        Master MA = new Master();
        blnStatus = MA.ProcessOperation(dsePageInfo, dseInputInfo, "INSERT");
        if (blnStatus == false)
        {
            strErrMessage = MA.ErrorMessage;
        }
        return blnStatus;
    }

    private bool UpdateData()
    {
        validateOwnerid();
        bool blnStatus = true;
        ScreenReader SR = new ScreenReader();
        dseInputInfo = SR.CaptureData(strPagesetRowID, frmObj, dsePageInfo,false);
        if (SR.errormessage != "")
        {
            strErrMessage = SR.errormessage;
            return false;
        }
        Master MA = new Master();
        blnStatus = MA.ProcessOperation(dsePageInfo, dseInputInfo, "UPDATE");
        if (blnStatus == false)
        {
            strErrMessage = MA.ErrorMessage;
        }
        return blnStatus;
    }

    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString();
        this.Title = "MaxBlox";
    }
    private bool isInteger(string inp)
    {
        if (inp.Trim().Length == 0) return false;
        try
        {
            int i = Convert.ToInt32(inp);
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }
    private bool isDateTime(string inp)
    {
        if (inp.Trim().Length == 0) return false;
        try
        {
            //30-11-2007 13:53:13
            //DateTime dt = DateTime.Parse(inp);
            DateTime dt = DateTime.ParseExact(inp,dtFormat, null);
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }
    private bool validate()
    {
        try
        {
            //string ret = p_job_schedules_jb_sch_id.Text;            
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }
    protected void btnSave_ServerClick(object sender, EventArgs e)
    {
        //lbl_message.Text = "sanal";
        //return;         
        //string ret = p_help_help_desc.Text;   
        //if (!validate()) return;
        if (SaveData())
        {
            //Response.Write("Data Inserted Successfully");
            string refURL = getRefURL();
            if (refURL.Length > 0)
                Response.Redirect(refURL);
            else
                lbl_message.Text =wrapItAsMessage("&nbsp;<img src='Images/info.gif' border='0'>&nbsp;Data Inserted Successfully",false);//changed by prithi on 07-Aug-2008 
        }
        else
        {
            lbl_message.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. Error:" + HttpUtility.HtmlEncode(ErrorMessage),true);
        }
    }
    private string wrapItAsMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }
    protected void btnUpdate_ServerClick(object sender, EventArgs e)
    {
        //if (!validate()) return;
        if (UpdateData())
        {
            string refURL = getRefURL();
            if (refURL.Length > 0)
                Response.Redirect(refURL);
            else
                lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/info.gif' border='0'>&nbsp;Data Updated Successfully",false);//changed by prithi on 07-Aug-2008 
        }
        else
        {
            lbl_message.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Update not successful. Error:" + HttpUtility.HtmlEncode(ErrorMessage), true);
        }
    }

    protected void btnreset_ServerClick(object sender, EventArgs e)
    {
        //Response.Redirect(Request.RawUrl);
        try
        {
            if (p_format_masks_type.Items.Count>0)   p_format_masks_type.SelectedIndex = 0;
            
        }
        catch (Exception ee)
        {

        }
    }
    private string getRefURL()
    {
        string ret = "";
        try
        {
            return hfRequestURL.Value;
            //DynamicDisplayI di = new DynamicDisplayI();
            //HiddenField hf = (HiddenField)di.FindControl(this.Controls, "hf_ref_url");
            //ret = hf.Value;
            //di = null;
            //return ret;
        }
        catch (Exception e)
        {
            return "";
        }

    }
    
    public string ErrorMessage
    {
        get
        {
            return this.strErrMessage;
        }
    }

    private void getpageicons() // Added by srivatsan to get page icon
    {
        PageIcons icons = new PageIcons();
        HDDatabase HDD = new HDDatabase();
        try
        {
            imgliteral.Text = "&nbsp;" + icons.geticontextfrompageset(Request.QueryString["pgs_id"].ToString(), 2) + "&nbsp;";
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error :getpageicons() " + ex.Message);
            imgliteral.Text = "&nbsp;<img src =" + PageIcons.strdefaulticon.ToString() + "><img>&nbsp;";
        }
        finally
        {
            icons = null;
            HDD = null;
        }
    }

    private void loadOwneridDropDown() // Added by srivatsan for owner id change
    {
        HDDatabase Hdd = new HDDatabase();
        BindControl BC = new BindControl();
        //DataSet ds = new DataSet();
        DataTable dt = null;
        try
        {

            if (Request.QueryString["PK"] == null)
            {
                p_format_masks_owner_id.Value = Session["user_afrowid"].ToString();
                txt_p_format_masks_owner_id.Text = Session["userid"].ToString();

            }
            if (Request.QueryString["PK"] != null)
            {
                if (Request.QueryString["CPY"] != null)
                {
                    p_format_masks_owner_id.Value = Session["user_afrowid"].ToString();
                    txt_p_format_masks_owner_id.Text = Session["userid"].ToString();
                }

            }

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : loadOwneridDropDown :" + ex.Message);
        }
        finally
        {
            Hdd = null;
            BC = null;
            dt = null;
        }


    }


    private bool validateOwnerid()
    {
        bool status = false;
        BindControl BC = new BindControl();
        HDDatabase HDD = new HDDatabase();
        DataSet dsBind = new DataSet();
        string sql = BC.GetBindSql("f496930dfe0b690f");
        dsBind = HDD.GetDataset(sql);
        if (dsBind != null)
        {
            if (dsBind.Tables.Count > 0)
            {
                if (dsBind.Tables[0].Rows.Count > 0)
                {
                    DataRow[] drrbind = dsBind.Tables[0].Select("fld = '" + txt_p_format_masks_owner_id.Text.Trim().Replace("'", "''") + "'");

                    if (drrbind.Length > 0)
                    {
                        p_format_masks_owner_id.Value = drrbind[0]["val"].ToString();
                        status = true;
                    }
                }
            }
        }
        if (status != true)
        {
            //lbl_message.Text = "<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp; Error: Invalid data for Owner :" + txt_ownerid.Text;
            lbl_message.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp; Error: Invalid data for Owner :" + HttpUtility.HtmlEncode(txt_p_format_masks_owner_id.Text),true);

        }
        return status;

    }


    private void CheckForChangeOwner()  // Added by srivatsan to Check if user can change owner
    {
        try
        {
            security sec = new security();
            bool status = false;
            status = sec.getRightsForMRUObjects("ps_pageset", "change_owner");
            if (status == false)
            {
                txt_p_format_masks_owner_id.Enabled = false;
                imgOwnerSearch.Visible = false;
            }
            sec = null;
        }
        catch
        {

        }
    }

    #region
    //private void loadOwneridDropDown() // Added by srivatsan for owner id change
    //{
    //    HDDatabase Hdd = new HDDatabase();
    //    BindControl BC = new BindControl();
    //    //DataSet ds = new DataSet();
    //    DataTable dt = null;
    //    try
    //    {
    //        string bindid = Hdd.GetColumnValue("select mem_value3 from sy_acr_mem where acr_id = 'cee69885ce44589c' and mem_id = 'owner_id'");
    //        BC.Bind(bindid, p_format_masks_owner_id, ref dt);

    //        if (Session["user_afrowid"].ToString() == "e51e0327224a2eb9")
    //        {
    //            p_format_masks_owner_id.Items.Add(new ListItem(Session["userid"].ToString(), Session["user_afrowid"].ToString()));
    //        }

    //        if (Request.QueryString["PK"] == null)
    //        {
    //            p_format_masks_owner_id.SelectedValue = Session["user_afrowid"].ToString();
    //        }
    //        if (Request.QueryString["PK"] != null)
    //        {
    //            if (Request.QueryString["CPY"] != null)
    //            {
    //                p_format_masks_owner_id.SelectedValue = Session["user_afrowid"].ToString();
    //            }

    //        }

    //    }
    //    catch (Exception ex)
    //    {
    //        LogWriter.WriteLog("Error : loadOwneridDropDown :" + ex.Message);
    //    }
    //    finally
    //    {
    //        Hdd = null;
    //        BC = null;
    //        dt = null;
    //    }


    //}
    #endregion
}
